package com.qf.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsStorageMapper;
import com.qf.pojo.DtsStorage;
import com.qf.service.StorageService;
import com.qf.util.AliyunOSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class StorageServiceImpl implements StorageService {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Autowired
    DtsStorageMapper storageMapper;

    @Override
    public DtsStorage uploadFile(String name, Integer size, String type, String objectName, byte[] bytes) throws Exception {
        //上传图片到 Oss
        String url = AliyunOSSUtil.uploadImage(endpoint, accessKeyId, accessKeySecret, bucketName, objectName, bytes);
        //存储DtsStorage到数据库
        DtsStorage storage = new DtsStorage();
        storage.setUrl(url); //图片的url路径
        storage.setType(type);//图片的类型
        storage.setSize(size); //文件的大小
        storage.setKey(objectName); //文件的唯一名称
        storage.setName(name); //文件的原始名称
        storage.setDeleted(false);
        storage.setAddTime(new Date());
        storage.setUpdateTime(new Date());
        //存储到数据库
        storageMapper.insert(storage);


        return storage;
    }

    @Override
    public Map<String, Object> findPage(Integer page, Integer limit, String sort, String order,String key,String name) {
        IPage page1 = new Page(page,limit);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("deleted",false);
        if(!StringUtils.isEmpty(key)){
            wrapper.like("`key`", key);
        }
        if(!StringUtils.isEmpty(name)){
            wrapper.like("`name`", name);
        }
        //降序，升序排序
        if("desc".equalsIgnoreCase(order)) {
            wrapper.orderByDesc(sort);
        }else{
            wrapper.orderByAsc(sort);
        }

        wrapper.eq("deleted", 0);

        storageMapper.selectPage(page1,wrapper);

        Map<String,Object> map = new HashMap<>();
        map.put("total",page1.getTotal());
        map.put("items",page1.getRecords());
        return map;


    }

    @Override
    public void deleteStorage(DtsStorage dtsStorage) {

        QueryWrapper wrapper = new QueryWrapper();


        storageMapper.deleteById(dtsStorage.getId());
    }
}
